package com.wangzhixuan.controller;

import com.wangzhixuan.constant.SystemConstant;
import com.wangzhixuan.db.bean.Customer;
import com.wangzhixuan.db.bean.Department;
import com.wangzhixuan.db.bean.Doctor;
import com.wangzhixuan.db.bean.Order;
import com.wangzhixuan.service.CustomerService;
import com.wangzhixuan.service.DepartmentService;
import com.wangzhixuan.service.DoctorService;
import com.wangzhixuan.service.OrderService;
import com.wangzhixuan.util.HttpUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/")
public class IndexController  extends BaseController{
    @Autowired
    private CustomerService customerService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private WxMpService wxMpService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public void base(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        String basePath = HttpUtils.getBasePath(request);
        try {
            response.sendRedirect(basePath + "/index.htm");
        } catch (IOException ex) {
            Logger.getLogger(IndexController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public void login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        String basePath = HttpUtils.getBasePath(request);
        try {
            String redrectUrl = basePath + "/code";
            redrectUrl = redrectUrl.replaceAll(":80","");
            String authUrl = wxMpService.oauth2buildAuthorizationUrl(redrectUrl,WxConsts.OAUTH2_SCOPE_USER_INFO, "index.htm");
            response.sendRedirect(authUrl);
        } catch (IOException ex) {
            Logger.getLogger(IndexController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    @RequestMapping("/index.htm")
    public String index(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        String tab=request.getParameter("tab");
        if(tab==null||"".equals(tab)){
            tab="1";
        }
        Customer currentCustomer = getCurrentCustomer(request);
        List<Doctor> doctors=doctorService.getAttentionDoctors(currentCustomer.getId());
        List<Order> orders=orderService.getOrdersByCustomer(currentCustomer.getId());
        Customer customer=customerService.getCustomerById(currentCustomer.getId());
        List<Department> depts=departmentService.getBaseDepartment();

        modelMap.put("depts", depts);
        modelMap.put("tab", tab);
        modelMap.put("doctors", doctors);
        modelMap.put("orders", orders);
        modelMap.put("customer", customer);
        return "index";
    }

    @ResponseBody
    @RequestMapping(value = "/code")
    public String accessCode(HttpServletRequest request, HttpServletResponse response, @RequestParam("code") String code, @RequestParam("state") String state) {
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
            String openId=wxMpUser.getOpenId();

            Customer customer = customerService.getCustomerByOpenId(openId);
            if(customer == null){
                String nickname = wxMpUser.getNickname();
                int sex = wxMpUser.getSexId();
                if(sex==1){
                    sex=0;
                }else{
                    sex=1;
                }
                customer = new Customer();
                customer.setOpenId(openId);
                customer.setName(nickname);
                customer.setSex(sex);
                customerService.addCustomer(customer);
            }
            HttpSession session = request.getSession();
            customer.setPassword("");
            session.setAttribute(SystemConstant.SESSION_CUSTOMER_KEY, customer);

            boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
            if (valid) {
                if (StringUtils.isBlank(state)) {
                    response.sendRedirect("/index.htm");
                } else {
                    response.sendRedirect(state);
                }
            }
        } catch (WxErrorException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return code;
    }

    @ResponseBody
    @RequestMapping(value = "/userinfo")
    public String getWxUserInfo(HttpServletRequest request, HttpServletResponse response,@RequestParam("redirect_url") String redirectUrl) {
        String basePath = HttpUtils.getBasePath(request);
        try {
            String redrectUrl = basePath + "/code";
            String authUrl = wxMpService.oauth2buildAuthorizationUrl(redrectUrl,WxConsts.OAUTH2_SCOPE_USER_INFO, redirectUrl);
            //response.sendRedirect(basePath + "/index.htm");
            response.sendRedirect(authUrl);
        } catch (IOException ex) {
            Logger.getLogger(IndexController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "success";
    }

    @ResponseBody
    @RequestMapping(value = "/isPerfect.json")
    public boolean isPerfect(HttpServletRequest request, HttpServletResponse response) {
        boolean isPerfect=true;
        Customer customer=getCurrentCustomer(request);
        customer=customerService.getCustomerByOpenId(customer.getOpenId());
        if(customer.getCellphone()==null||customer.getClinic()==null||customer.getAddress()==null){
            isPerfect=false;
        }
        return isPerfect;
    }

    @ResponseBody
    @RequestMapping(value = "/getNotices.json")
    public List<Doctor> getNotices(HttpServletRequest request, HttpServletResponse response) {
        Customer currentCustomer = getCurrentCustomer(request);
        List<Doctor> doctors=doctorService.getAttentionDoctors(currentCustomer.getId());
        return doctors;
    }
    @ResponseBody
    @RequestMapping(value = "/getOrders.json")
    public List<Order> getOrders(HttpServletRequest request, HttpServletResponse response) {
        Customer currentCustomer = getCurrentCustomer(request);
        List<Order> orders=orderService.getOrdersByCustomer(currentCustomer.getId());
        return orders;
    }
    @ResponseBody
    @RequestMapping(value = "/getCustomer.json")
    public Customer getCustomer(HttpServletRequest request, HttpServletResponse response) {
        Customer currentCustomer = getCurrentCustomer(request);
        Customer customer=customerService.getCustomerById(currentCustomer.getId());
        return customer;
    }
}
